<template>
  <div id="app">
    <router-view />
    <theme-picker />
    <el-dialog
      title="温馨提示"
      :visible.sync="commonDialog"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      top="340px !important" 
    >
      <div>{{ message }}</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clickViewOrder">查看订单</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ThemePicker from "@/components/ThemePicker";
import { countOrder } from "@/api/system/orderList/order";
import { login, logout, getInfo } from "@/api/login";
import { getToken } from "@/utils/auth";

const msg = new window.SpeechSynthesisUtterance();

export default {
  name: "App",
  components: { ThemePicker },
  data() {
    return {
      commonDialog: false,
      message: "您有新的订单，请注意查收",
      reconnectTimes: 0, // 重连次数
      reconnectTimesMax: 0,
      reconnectInterval: 1000 * 30, // 重连间隔5秒
      url: process.env.VUE_APP_WEBSOCKET_URL,
      ws: null,
      timeout: 1000 * 50,
      serverTimeoutObj: null,
      orderNumber: "",
      orderStatus: 1,
      storeId: "",
    };
  },
  created() {
    if (getToken()) {
      this.GetInfo();
    }
  },
  mounted() {
    this.beforeDestroys();
    this.initWebSocket();
  },

  methods: {
    // 获取用户信息
    GetInfo() {
      getInfo()
        .then((res) => {
          this.storeId = res.storeId;
        })
        .catch((error) => {});
    },
    initWebSocket() {
      this.ws = new WebSocket(this.url);

      this.ws.onopen = () => {
        console.log("WebSocket连接成功");
        this.reset().start();
      };

      this.ws.onerror = () => {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      };

      this.ws.onclose = () => {
        console.log("WebSocket连接已关闭");
        this.reconnect();
      };
      let _this = this;
      this.ws.onmessage = function (event) {
        console.log("收到WebSocket消息: ", JSON.parse(event.data));
        let data = JSON.parse(event.data);
        console.log(data, "datadatadata");

        if (!_this.storeId || _this.storeId == data.storeId) {
          if (data.code == 200 && data.type == 1 && !data.isSendPc) {
            _this.orderNumber = data.orderId;
            _this.orderStatus = data.orderStatus;
            _this.getCountOrder();
          }
          if (data.code == 200 && data.type == 2 && !data.isSendPc) {
            // 只播报当前门店
            _this.message = data.message;

            _this.playVoice();
          }
        }
      };
      // 其他的ws事件处理...
    },
    reconnect() {
      if (
        this.reconnectTimesMax === 0
          ? true
          : this.reconnectTimes < this.reconnectTimesMax
      ) {
        // 最多重连5次
        setTimeout(() => {
          this.reconnectTimes++;
          this.initWebSocket();
        }, this.reconnectInterval);
      } else {
        console.error("重连次数达到上限，不再尝试重连");
      }
    },
    reset() {
      clearTimeout(this.serverTimeoutObj);
      return this;
    },
    start() {
      var self = this;
      this.serverTimeoutObj = setInterval(function () {
        if (self.ws.readyState === 1) {
          console.log("连接状态，发送消息保持连接");
          self.ws.send("ping");
          self.reset().start(); // 如果获取到消息，说明连接是正常的，重置心跳检测
        } else {
          console.log("断开状态，尝试重连");
          self.initWebSocket();
        }
      }, self.timeout);
    },

    beforeDestroys() {
      if (this.ws) {
        this.ws.close(); // 在组件销毁前关闭WebSocket连接
      }
    },

    playVoice() {
      // message 假设message是你拼接好的文本信息
      this.handleSpeak(); // 传入需要播放的文字
    },
    // 语音播报的函数
    // 比如你从后端接收完数据，并且自己拼接好以后，就可以直接调这个方法，传入你的文本，就可以播放了
    handleSpeak(text) {
      msg.text = this.message; // 文字内容: 小朋友，你是否有很多问号
      msg.lang = "zh-CN"; // 使用的语言:中文
      msg.volume = 20; // 声音音量：1
      msg.rate = 1.5; // 语速：1
      msg.pitch = 10; // 音高：1
      console.log(msg, 888);
      window.speechSynthesis.cancel();
      window.speechSynthesis.speak(msg);
    },
    broadcast() {
      window.speechSynthesis.cancel();
      const textToSpeak = "您有新的订单";
      const speechSynthesisUtterance = new SpeechSynthesisUtterance(
        textToSpeak
      );
      console.log(speechSynthesisUtterance, 888);
      // 可选：设置语音属性
      speechSynthesisUtterance.lang = "zh-CN"; // 设置语言为中文
      speechSynthesisUtterance.rate = 1; // 设置语速（1为正常速度）
      speechSynthesisUtterance.pitch = 1; // 设置音调（1为正常音调）
      speechSynthesisUtterance.volume = 1; // 设置音量（0到1之间）

      // 开始播报
      window.speechSynthesis.speak(speechSynthesisUtterance);
    },
    //获取订单数量
    getCountOrder() {
      if (this.commonDialog == false) {
        this.commonDialog = true;
      }
      return;
      let path = this.$router.history.current.path;
      countOrder().then((res) => {
        var total = localStorage.getItem("total");
        if (!total && path !== "/orderList/order") {
          localStorage.setItem("total", res.data);
        } else {
          if (total != res.data && path !== "/orderList/order") {
            localStorage.setItem("total", res.data);
          }
        }
        if (this.commonDialog == false) {
          this.commonDialog = true;
        }
      });
    },
    clickViewOrder() {
      console.log(this.orderNumber, "this.orderNumber");
      this.commonDialog = false;

      console.log(this.$route.path); // 输出当前路径
      //
      if (this.$route.path == "/orderList/order") {
        // location.reload();
        this.$router.replace();
        return;
      }
      if (this.orderNumber) {
        this.$router.push({
          path: "/orderList/order",
          query: {
            order: this.orderNumber,
            orderStatus:this.orderStatus
          },
        });
      } else {
        this.$router.push({
          path: "/orderList/order",
        });
      }
    },
    cancel() {
      this.commonDialog = false;
    },
  },
  metaInfo() {
    return {
      title:
        this.$store.state.settings.dynamicTitle &&
        this.$store.state.settings.title,
      titleTemplate: (title) => {
        return title
          ? `${title} - ${process.env.VUE_APP_TITLE}`
          : process.env.VUE_APP_TITLE;
      },
    };
  },
};
window.speechSynthesis.onstart = function (event) {
  console.log("开始播报");
};

window.speechSynthesis.onend = function (event) {
  console.log("播报结束");
};

window.speechSynthesis.onerror = function (event) {
  console.error("播报出错:", event.error);
};
</script>

<style scoped>
#app .theme-picker {
  display: none;
}

.column-center {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
}
/* ::v-deep .el-dialog .dialog {
    ;
} */
/* 滚动条整体样式 */
::-webkit-scrollbar {
    width: 8px; /* 纵向滚动条宽度 */
    height: 8px; /* 横向滚动条高度 */
}

/* 滚动条轨道 */
::-webkit-scrollbar-track {
    background-color: #f1f1f1; /* 轨道背景颜色 */
    border-radius: 4px; /* 轨道圆角 */
}

/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
    background-color: #c1c1c1; /* 滑块背景颜色 */
    border-radius: 4px; /* 滑块圆角 */
}

/* 滚动条滑块悬停状态 */
::-webkit-scrollbar-thumb:hover {
    background-color: #a8a8a8; /* 悬停时滑块背景颜色 */
}
</style>

